# # 绘制单个的样本分布图
# import pandas as pd
# import matplotlib.pyplot as plt
# import cartopy.crs as ccrs
# import cartopy.feature as cfeature
# from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
#
# # --- 1. 定义文件路径并加载数据 ---
# # filepath = '/home/liudd/deeplearing/standard_train_ocean2.csv'
# # filepath = '/home/liudd/deeplearing/standard_train_ocean3.csv'
# # filepath = '/home/liudd/deeplearing/standard_train_ocean4.csv'
# # filepath = '/home/liudd/deeplearing/standard_train_ocean5.csv'
# # filepath = '/home/liudd/deeplearing/standard_train_ocean6.csv'
# filepath = '/home/liudd/03_land_inversion/01data/ocean_merged_201902_202004_2025.csv'
#
# # df = pd.read_csv(filepath, low_memory=False)
# #
#
#
# try:
#     df = pd.read_csv(filepath)
#     print(f"成功加载 {len(df)} 个数据点。")
# except FileNotFoundError:
#     print(f"错误：找不到文件 '{filepath}'。请检查路径是否正确。")
#     exit()
#
# df = df[df['fy_clt'] != 7]
# filtered_data_size = len(df)
# print(f'筛选后的数据总量为：{filtered_data_size}')
# # --- 提取经纬度数据 ---
# lons = df['fy_lon'].values
# lats = df['fy_lat'].values
#
# # --- 2. 设置地图和绘图参数 ---
# fig = plt.figure(figsize=(10, 8)) # 调整了尺寸以更好地适应范围
# ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
#
# # --- 关键: 固定地图的经纬度范围 ---
# ax.set_extent([30, 170, -70, 70], crs=ccrs.PlateCarree())
#
# # --- 3. 添加地图特征，并设置背景色为白色 ---
# ax.add_feature(cfeature.COASTLINE, edgecolor='black', linewidth=0.8)
# ax.add_feature(cfeature.BORDERS, linestyle=':', edgecolor='gray', linewidth=0.5)
# ax.add_feature(cfeature.LAND, edgecolor='black', facecolor='white')
# ax.add_feature(cfeature.OCEAN, facecolor='white')
#
# # --- 4. 核心：绘制二维直方图 (2D Histogram) ---
# # --- 关键修正: 根据 extent 范围精确计算 bins ---
# # 经度范围 170-30=140°, 纬度范围 70-(-70)=140°
# hist = ax.hist2d(
#     lons,
#     lats,
#     bins=[140, 140], # 修正为 [140, 140] 以匹配1°x1°网格
#     cmap='jet',
#     cmin=1,
#     transform=ccrs.PlateCarree()
# )
#
# # --- 5. 添加颜色条 (Colorbar) ---
# cbar = fig.colorbar(hist[3], ax=ax, orientation='vertical', pad=0.03, shrink=0.85)
# cbar.set_label('Count', fontsize=12) # 添加标签
#
# # --- 6. 优化网格线和坐标轴标签 ---
# # 使用 set_xticks/yticks 精确控制标签位置
# ax.set_xticks(range(40, 180, 20), crs=ccrs.PlateCarree())
# # ax.set_yticks(range(-60, 80, 20), crs=ccrs.PlateCarree())
# ax.set_yticks(range(-60, 81, 20), crs=ccrs.PlateCarree())
# ax.xaxis.set_major_formatter(LongitudeFormatter())
# ax.yaxis.set_major_formatter(LatitudeFormatter())
# ax.grid(linewidth=0.5, color='gray', alpha=0.5, linestyle='--')
# # 调整字体大小
# ax.tick_params(axis='both', which='major', labelsize=12)
#
#
# # --- 7. 添加标题 ---
# plt.title('All clouds data distribution', fontsize=20)
#
# # --- 8. 保存并显示图像 ---
# # --- 关键修正: 先保存，再显示，并修正拼写错误 ---
# save_path = '/home/liudd/03_land_inversion/06plot_map/ocean_all_distribution_map.png'
# plt.savefig(save_path, dpi=300, bbox_inches='tight')
# print(f"图像已成功保存到: {save_path}")
#
# plt.show()

# 批量绘制样本分布图
import pandas as pd
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
import numpy as np
# 【修改点1, 步骤A】: 导入用于精确控制颜色条的工具
from mpl_toolkits.axes_grid1 import make_axes_locatable

# --- 1. 准备所有文件路径和对应的子图标题 ---
filepaths = [
    '/home/liudd/deeplearing/standard_train_ocean2.csv',
    '/home/liudd/deeplearing/standard_train_ocean3.csv',
    '/home/liudd/deeplearing/standard_train_ocean4.csv',
    '/home/liudd/deeplearing/standard_train_ocean5.csv',
    '/home/liudd/deeplearing/standard_train_ocean6.csv',
    '/home/liudd/03_land_inversion/01data/ocean_merged_201902_202004_2025.csv'
]

titles = [
    'water clouds data distribution',
    'supercooled clouds data distribution',
    'mix clouds data distribution',
    'ice clouds data distribution',
    'cirrus clouds data distribution',
    'All clouds data distribution'
]

# --- 2. 创建 2x3 的子图网格 ---
fig, axes = plt.subplots(
    nrows=2,
    ncols=3,
    figsize=(20, 11),  # 可以微调尺寸
    subplot_kw={'projection': ccrs.PlateCarree()}
)

print("开始绘制 6 张子图...")

# --- 3. 循环遍历每个文件和对应的子图(ax) ---
for i, ax in enumerate(axes.flatten()):
    filepath = filepaths[i]
    title = titles[i]

    print(f"正在处理: {filepath}")

    try:
        df = pd.read_csv(filepath)
    except FileNotFoundError:
        print(f"--> 警告：找不到文件 '{filepath}'，跳过此图。")
        ax.set_title(f"{title}\n(数据文件未找到)", color='red')
        continue

    lons = df['fy_lon'].values
    lats = df['fy_lat'].values

    ax.set_extent([30, 170, -70, 70], crs=ccrs.PlateCarree())
    ax.add_feature(cfeature.COASTLINE, edgecolor='black', linewidth=0.8)
    ax.add_feature(cfeature.BORDERS, linestyle=':', edgecolor='gray', linewidth=0.5)
    ax.add_feature(cfeature.LAND, edgecolor='black', facecolor='white')
    ax.add_feature(cfeature.OCEAN, facecolor='white')

    hist = ax.hist2d(
        lons,
        lats,
        bins=[140, 140],
        cmap='jet',
        cmin=1,
        transform=ccrs.PlateCarree()
    )

    # --- 【修改点1, 步骤B】: 使用新方法创建宽度固定的颜色条 ---
    # 创建一个与 ax 绑定的分隔器
    divider = make_axes_locatable(ax)
    # 在 ax 右侧附加一个新的 cax (颜色条的专属坐标轴)
    # size="5%" 表示新 cax 的宽度是 ax 宽度的 5%
    # pad=0.1 表示 cax 和 ax 之间的距离
    cax = divider.append_axes("right", size="5%", pad=0.1, axes_class=plt.Axes)
    # 将颜色条绘制在这个固定的 cax 上
    cbar = fig.colorbar(hist[3], cax=cax)
    # cbar.set_label('Count')
    # ----------------------------------------------------

    ax.set_xticks(range(40, 180, 20), crs=ccrs.PlateCarree())
    # ax.set_yticks(range(-60, 81, 20), crs=ccrs.PlateCarree())
    ax.set_yticks(np.arange(-70, 81, 20), crs=ccrs.PlateCarree())  # np.arange(-70, 71, 20)
    ax.xaxis.set_major_formatter(LongitudeFormatter())
    ax.yaxis.set_major_formatter(LatitudeFormatter())
    ax.grid(linewidth=0.5, color='gray', alpha=0.5, linestyle='--')
    ax.tick_params(axis='both', which='major', labelsize=10)
    ax.set_title(title, fontsize=14)

# --- 4. 【修改点2】: 调整整体布局，减小列间距 ---
# wspace 控制子图的水平间距，值越小，间距越窄
# hspace 控制子图的垂直间距
fig.subplots_adjust(wspace=0.15, hspace=0.2)
# ----------------------------------------------

# 保存整个图像
save_path = '/home/liudd/03_land_inversion/06plot_map/all_ocean_distributions_adjusted.png'
plt.savefig(save_path, dpi=500, bbox_inches='tight')
print(f"\n所有图像已成功保存到: {save_path}")

# 显示图像
plt.show()